﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Areas.Admin.Models;
using System.Data;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 信息回收站控制器
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class DocRecycleBinController : Common.AdminBaseController
    {

        /// <summary>
        /// 通用方法逻辑类
        /// </summary>
        private BLL.Common commonBLL = new BLL.Common();
        /// <summary>
        /// 文档逻辑类
        /// </summary>
        private BLL.Document documentBLL = new BLL.Document();
        /// <summary>
        /// 信息回收站首页
        /// </summary>
        /// <returns>首页页面</returns>
        [AuthorityActionFilter("m_DocumentRecycleBin", Order = 1)]
        [LogPageActionFilter("信息回收站", Order = 2)]
        public ActionResult Index()
        {
            int pageIndex = 1;
            string strWhere = "FEntityNo='" + Common.GlobalConstant.ENTITYNO + "' and FRecycle='Y'" + " and FEmplNo='" + Common.OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO) + "'";
            List<DocumentGridModel> documentList = GetDocRecycleBinList(strWhere, pageIndex);

            return View(documentList);
        }
        /// <summary>
        /// Grid调用方法
        /// </summary>
        /// <returns>Grid页面</returns>
        public ActionResult DocRecycleBinListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();


            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }

            string strWhere = "FEntityNo='" + Common.GlobalConstant.ENTITYNO + "' and FRecycle='Y'" + " and FEmplNo='" + Common.OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO) + "'";
            List<DocumentGridModel> documentList = GetDocRecycleBinList(strWhere, pageIndex);
            return PartialView("DocRecycleBinListPartial", documentList);
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="strWhere">数据查询条件</param>
        /// <param name="pageIndex">第几页开始</param>
        /// <returns>查询获得数据</returns>
        private List<DocumentGridModel> GetDocRecycleBinList(string strWhere, int pageIndex)
        {
            string fiedls = "*";
            int total;
            string tableName = "v_documentRecycle";
            int pageRowSize = 15;
            string queryWhere = strWhere;
            DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageRowSize, pageIndex, queryWhere, "FPubDate", 1, out total);
            List<DocumentGridModel> documentAllList = new List<DocumentGridModel>();
            List<DocumentGridModel> documentList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);

            for (int i = 0; i < total; i++)
            {
                documentAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (documentList.Count > i)
                {
                    documentAllList[((pageIndex - 1) * pageRowSize) + i] = documentList[i];
                }
            }
            return documentAllList;
        }
        /// <summary>
        /// 删除回收站的信息
        /// </summary>
        /// <param name="docIds">信息编号列表</param>
        /// <returns>结果</returns>
        [HttpPost]
        public string DeleteDocument(string docIds)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            string entityNo = GlobalConstant.ENTITYNO;
            string[] docIdArray = docIds.Split(',');
            if (docIdArray.Length > 0)
            {
                try
                {
                    List<decimal> docIdList = new List<decimal>();
                    bool isSuccess = true;
                    foreach (string s in docIdArray)
                    {
                        decimal tmp = 0;
                        if (decimal.TryParse(s, out tmp))
                        {
                            docIdList.Add(tmp);
                        }
                        else
                        {
                            isSuccess = false;
                            break;
                        }
                    }
                    if (!isSuccess)
                    {
                        errorMessage = "信息编号参数解析错误";
                    }
                    else
                    {
                        documentBLL.DelDocumentAndAttach(docIdList, Common.GlobalConstant.ENTITYNO);
                        try
                        {
                            string docNoArray = "";
                            foreach (decimal docId in docIdList)
                            {
                                docNoArray += docId + ",";
                            }
                            docNoArray = docNoArray.Substring(0, docNoArray.LastIndexOf(','));
                            List<string> listImgPath = documentBLL.getDocFThumbSrvFileName(Common.GlobalConstant.ENTITYNO, docNoArray);//缩略图路径
                            List<string> listAttach = documentBLL.getDocAttachS(Common.GlobalConstant.ENTITYNO, docNoArray, "DOC");//附件路径
                            List<string> listSrvFileNames = documentBLL.getDocSrvFileNameByOffice(Common.GlobalConstant.ENTITYNO, docNoArray);//获取Office文件的路径

                            DelAttach(listAttach);//删除附件
                            DelImgS(listImgPath);//删除缩略图

                            DelOffice(listSrvFileNames);//删除Office文件

                            jsonstr = "SUCCESS";
                        }
                        catch (Exception ee)
                        {
                            errorMessage = "信息已删除,但是相关文件删除出错:" + ee.Message;
                        }

                    }
                }
                catch (Exception ee)
                {
                    errorMessage = "操作异常:" + ee.Message;
                }
            }
            else
            {
                errorMessage = "信息编号参数错误";
            }

            if (jsonstr == "FAILED")
            {
                jsonstr += "FAILED|" + errorMessage;
            }
            return jsonstr;
        }
        /// <summary>
        /// 清空回收站的信息
        /// </summary>
        /// <param name="docIds">信息编号列表</param>
        /// <returns>结果</returns>
        [HttpPost]
        public string ClearRecycleBin()
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            string entityNo = GlobalConstant.ENTITYNO;
            List<decimal> docIdList = documentBLL.getDocIDByFRecycle(entityNo, OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO));//获取该员工发布的所有删除状态为Y的信息ID
            documentBLL.DelDocumentAndAttach(docIdList, Common.GlobalConstant.ENTITYNO);
            try
            {
                string docNoArray = "";
                foreach (decimal docId in docIdList)
                {
                    docNoArray += docId + ",";
                }
                docNoArray = docNoArray.Substring(0, docNoArray.LastIndexOf(','));
                List<string> listImgPath = documentBLL.getDocFThumbSrvFileName(Common.GlobalConstant.ENTITYNO, docNoArray);//缩略图路径
                List<string> listAttach = documentBLL.getDocAttachS(Common.GlobalConstant.ENTITYNO, docNoArray, "DOC");//附件路径
                List<string> listSrvFileNames = documentBLL.getDocSrvFileNameByOffice(Common.GlobalConstant.ENTITYNO, docNoArray);//获取Office文件的路径

                DelAttach(listAttach);//删除附件
                DelImgS(listImgPath);//删除缩略图

                DelOffice(listSrvFileNames);//删除Office文件

                jsonstr = "SUCCESS";
            }
            catch (Exception ee)
            {
                errorMessage = "信息已删除,但是相关文件删除出错:" + ee.Message;
            }

            if (jsonstr == "FAILED")
            {
                jsonstr += "FAILED|" + errorMessage;
            }
            return jsonstr;
        }
        /// <summary>
        /// 信息还原
        /// </summary>
        /// <param name="docIds">信息编号列表</param>
        /// <returns>结果</returns>
        [HttpPost]
        public string Restore(string docIds)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            string entityNo = GlobalConstant.ENTITYNO;
            string[] docIdArray = docIds.Split(',');
            if (docIdArray.Length > 0)
            {
                try
                {
                    List<decimal> docIdList = new List<decimal>();
                    bool isSuccess = true;
                    foreach (string s in docIdArray)
                    {
                        decimal tmp = 0;
                        if (decimal.TryParse(s, out tmp))
                        {
                            docIdList.Add(tmp);
                        }
                        else
                        {
                            isSuccess = false;
                            break;
                        }
                    }
                    if (!isSuccess)
                    {
                        errorMessage = "信息编号参数解析错误";
                    }
                    else
                    {
                        BLL.Document documentBLL = new BLL.Document();
                        documentBLL.UpdateDocRestore(docIdList);
                        jsonstr = "SUCCESS";
                    }
                }
                catch (Exception ee)
                {
                    errorMessage = "操作异常:" + ee.Message;
                }
            }
            else
            {
                errorMessage = "信息编号参数错误";
            }

            if (jsonstr == "FAILED")
            {
                jsonstr += "FAILED|" + errorMessage;
            }
            return jsonstr;
        }


        /// <summary>
        /// 转换数据
        /// </summary>
        /// <param name="listDocId">需转换LIST</param>
        /// <returns>逗号分隔字符串</returns>
        public string SetDocIds(List<decimal> listDocId)
        {
            string strDocIdS = string.Empty;
            foreach (decimal decDocId in listDocId)
            {
                strDocIdS += decDocId + ",";
            }
            return strDocIdS.Substring(0, strDocIdS.Length - 1);
        }



        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="listAttach">附件路径集合</param>
        public void DelAttach(List<string> listAttach)
        {
            foreach (string str in listAttach)
            {
                GenerateUtil.DeleteFile(str);
            }
        }


        /// <summary>
        /// 删除缩略图
        /// </summary>
        /// <param name="strImgPath">缩略图路径</param>
        public void DelImg(string strImgPath)
        {
            GenerateUtil.DeleteFile(strImgPath);
        }


        /// <summary>
        /// 删除多条缩略图
        /// </summary>
        /// <param name="listImgPath">路径集合</param>
        public void DelImgS(List<string> listImgPath)
        {
            foreach (string str in listImgPath)
            {
                GenerateUtil.DeleteFile(str);
            }
        }

        /// <summary>
        /// 删除单个office文件
        /// </summary>
        /// <param name="strSvrFileName">OFFICE文件路径</param>
        public void DelOffice(string strSvrFileName)
        {
            if (!string.IsNullOrEmpty(strSvrFileName))
            {
                GenerateUtil.DeleteFile(strSvrFileName);
            }
        }

        /// <summary>
        /// 删除多个office文件
        /// </summary>
        /// <param name="listSvrFileName">OFFICE文件路径集合</param>
        public void DelOffice(List<string> listSvrFileName)
        {
            foreach (string strSvrFileName in listSvrFileName)
            {
                if (!string.IsNullOrEmpty(strSvrFileName))
                {
                    GenerateUtil.DeleteFile(strSvrFileName);
                }
            }
        }

    }
}
